package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

public class XMLMapperBuilder {

    private Configuration configuration;


    Map<String, MappedStatement> mappedStement = configuration.getMappedStement();


    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }


    // 定义一个解析sql的mapper文件的方法
    public void parse(InputStream inputStream) throws DocumentException {
        Document read = new SAXReader().read(inputStream);
        Element rootElement = read.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> selectNodes = rootElement.selectNodes("//select");
        List<Element> insertNodes = rootElement.selectNodes("//insert");
        List<Element> updateNodes = rootElement.selectNodes("//update");
        List<Element> deleteNodes = rootElement.selectNodes("//delete");
        // 遍历删除节点
        tobeMappendStatament(namespace, deleteNodes);
        // 遍历更新节点
        tobeMappendStatament(namespace, updateNodes);
        // 遍历插入节点
        tobeMappendStatament(namespace, insertNodes);

        // 遍历查询方法
        for (Element selectNode : selectNodes) {
            String id = selectNode.attributeValue("id");
            String paramterType = selectNode.attributeValue("paramterType");
            String resultType = selectNode.attributeValue("resultType");
            String sqlText = selectNode.getTextTrim();
            String key = namespace + "."+id;
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sqlText);
            mappedStement.put(key,mappedStatement);

        }

    }

    private void tobeMappendStatament(String namespace, List<Element> nodes) {
        for (Element deleteNode : nodes) {
            String id = deleteNode.attributeValue("id");
            String paramterType = deleteNode.attributeValue("paramterType");

            String sqlText = deleteNode.getTextTrim();
            String key = namespace + "."+id;
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParamterType(paramterType);

            mappedStatement.setSql(sqlText);
            mappedStement.put(key,mappedStatement);
        }
    }
}
